<template>
  <div class="account-login">
    <el-form ref="formRef" label-width="70px" :model="account" :rules="rules" class="demo-ruleForm" status-icon>
      <el-form-item label="账号" prop="name" size="large">
        <el-input @focus="clearValidate('name')" v-model="account.name" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password" size="large">
        <el-input @focus="clearValidate('password')" type="password" v-model="account.password" show-password placeholder="请输入密码" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from "vue"
import { rules } from "../config/accout-config"
import type { ElForm } from "element-plus"
import { useStore } from "vuex"
import cache from "@/utils/cache"
export default defineComponent({
  setup() {
    const store = useStore()
    const account = reactive({
      name: cache.getLocation("name") ?? "",
      password: cache.getLocation("password") ?? ""
    })
    // 使用element-plus 的表单验证类型验证 获取某个实例的类型（InstanceType）
    const formRef = ref<InstanceType<typeof ElForm>>()

    // 登录
    const accoutLogin = (isKeepPassword: boolean) => {
      formRef.value?.validate((valid) => {
        if (!valid) return
        // 记住密码
        if (isKeepPassword) {
          cache.setLocation("name", account.name)
          cache.setLocation("password", account.password)
        } else {
          cache.deleteLocation("name")
          cache.deleteLocation("password")
        }
        store.dispatch("login/accoutLoginAction", { ...account })
      })
    }

    // 移除表单
    const clearValidate = (prop: any) => {
      formRef.value?.clearValidate(prop)
    }

    return {
      account,
      rules,
      accoutLogin,
      formRef,
      clearValidate
    }
  }
})
</script>
<style lang="less" scoped></style>
